package com.anli.config;

import com.alibaba.fastjson.JSON;
import com.anli.dao.TestLockMapper;
import com.anli.entity.StockInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @author: LI-CI-GAO
 * 作者: licigao
 * 日期: 2021/8/30  16:00
 * 描述:
 */
@Component
public class TestRedisListener implements MessageListener {

    @Autowired
    private TestLockMapper testLockMapper;

    @Autowired
    @Qualifier("redisTemplate10")
    private RedisTemplate<String,String> redisTemplate10;

    @Override
    public void onMessage(Message message, byte[] bytes) {

        try {
            String json = new String(message.getBody());
            String substring = json.substring(7, json.length());
            StockInfo stockInfo = JSON.parseObject(substring, StockInfo.class);
            //1、获取库存
            StockInfo stockInfo1 = testLockMapper.getStockInfo(stockInfo);
            //2、检验库存
            if((stockInfo1.getStock()-stockInfo.getStock())<0){
                //说明库存不足
            }else{
                //3、更新锁定库存
                StockInfo stockInfo2=new StockInfo();
                stockInfo2.setStockId(stockInfo.getStockId());
                stockInfo2.setGoodsId(stockInfo.getGoodsId());
                stockInfo2.setStock(stockInfo1.getStock()-stockInfo.getStock());
                stockInfo2.setVersion(stockInfo1.getVersion());
                int i = testLockMapper.updateStock2(stockInfo2);
                if(i==0){
                    //4、更新失败
                    String string = JSON.toJSONString(stockInfo);
                    System.out.println("=======加入队列2======"+string);
                    //redisTemplate10.convertAndSend("LOCK",string);
                }
                stockInfo2=null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
